import 'dart:math';

import 'package:flame/collisions.dart';
import 'package:flame/game.dart';
import 'package:flame/events.dart';
import 'package:flame/input.dart';
import 'package:flame/palette.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../component.dart';

class Game2 extends FlameGame with KeyboardEvents, TapDetector, PanDetector {
  late final HeroComponent player;
  late final RectangleHitbox box;

  @override
  Future<void> onLoad() async {
    final knobPaint = BasicPalette.blue.withAlpha(200).paint();
    final bgPaint = BasicPalette.blue.withAlpha(100).paint();
    player = HeroComponent();
    box = RectangleHitbox()..debugMode = false;
    player.add(box..debugMode = false);
    add(player);
  }

  final double step = 10;

  double _counter = 0;

  @override
  void onTap() {
    _counter++;
    player.rotateTo(_counter * pi / 2);
  }

  @override
  onTapCancel() {
    box.debugMode = false;
  }

  @override
  onTapDown(TapDownInfo info) {
    box.debugMode = true;
    box.debugColor = Colors.purple;
  }

  @override
  onTapUp(TapUpInfo info) {
    box.debugMode = false;
  }

  @override
  void onPanStart(DragStartInfo info) {}

  @override
  void onPanUpdate(DragUpdateInfo info) {
    player.move(info.delta.global);
  }

  @override
  void onPanEnd(DragEndInfo info) {
    box.debugMode = false;
  }

  @override
  void onPanCancel() {
    box.debugMode = false;
  }

  // 键盘事件
  @override
  KeyEventResult onKeyEvent(
      KeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
    final isKeyDown = event is KeyDownEvent;
    if (event.logicalKey == LogicalKeyboardKey.keyY && isKeyDown) {
      player.flip(y: true);
    }
    if (event.logicalKey == LogicalKeyboardKey.keyX && isKeyDown) {
      player.flip(x: true);
    }
    if (event.logicalKey == LogicalKeyboardKey.keyW && isKeyDown) {
      player.move(Vector2(0, -step));
    }

    if (event.logicalKey == LogicalKeyboardKey.keyS && isKeyDown) {
      player.move(Vector2(0, step));
    }

    if (event.logicalKey == LogicalKeyboardKey.keyA && isKeyDown) {
      player.move(Vector2(-step, 0));
    }

    if (event.logicalKey == LogicalKeyboardKey.keyD && isKeyDown) {
      player.move(Vector2(step, 0));
    }

    return super.onKeyEvent(event, keysPressed);
  }
}
